<template>
  <div
    class="app-container-flex"
    v-show="showDialog && !detailInfo.visible && !planDetailInfo.visible"
  >
    <div class="width100">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :clearType="clearType"
          :slipSelectRequest="slipSelectRequest"
          :filter-btn="filterInfo.searchBtn"
        >
        </NewPageFilter>
        <el-button @click="closeDetailList">订单页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <PopoverPrint
              ref="popoverShow"
              v-model:popoverVisible="popoverVisible"
              :canPrint="true"
              :templateArr="templateArr"
              @tempClick="tempClick"
              @print="handelPrint"
            ></PopoverPrint>
          </template>
          <template v-slot:filter-excel>
            <el-button @click="exportExcel()">导出excel </el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <GroupSelect
            @callback="groupSelect"
            @callbackVal="updateGroupSelections"
            :options="groupSelectInfo.options"
            v-model:selections="groupSelectInfo.selections"
          ></GroupSelect>
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <TableContainer
        v-if="groupFlag"
        class="groupFlag-container"
        :isGroupSearch="true"
        v-model:data="groupSelectInfo.data"
        :field-list="tableInfo.fieldList"
        :checkBox="false"
        :tabIndex="false"
        :pager="false"
        :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
        @exChange="exChange"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        :span-method="arraySpanMethod"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-orderNo="scope">
          {{ scope.row.orderNo }}
        </template>
        <template v-slot:col-planOrderNo="scope">
          <span>{{ scope.row.planOrderNo }}</span>
        </template>
        <template v-slot:col-assetName="scope">
          <span>{{ scope.row.assetName }}</span>
        </template>
      </TableContainer>
      <TableContainer
        v-else
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        v-model:query="filterInfo.query"
        :checkBox="false"
        :tabIndex="true"
        :field-list="tableInfo.fieldList"
        @pageInfo="pageInfo"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-planOrderNo="scope">
          <span class="slip-edit" @click="showPlanDetail(scope.row)">{{
            scope.row.planOrderNo
          }}</span>
        </template>
        <template v-slot:col-assetName="scope">
          <span>{{ scope.row.assetName }}</span>
        </template>
      </TableContainer>
    </div>
  </div>
  <SetPreference
    v-if="preferenceInfo.visible"
    v-model:visible="preferenceInfo.visible"
    :searchList="filterInfo.searchList"
    :fieldList="tableInfo.fieldList"
    :customizeUserVO="filterInfo.query.customizeUserVO"
    @callback="setPreferenceCallback"
  />
  <AdvancedSearch
    v-if="advancedSearchInfo.visible"
    v-model:visible="advancedSearchInfo.visible"
    :fieldList="tableInfo.fieldList"
    v-model:formData="advancedSearchInfo.data"
    @callback="advancedSearchCallback"
  />
  <order-detail
    v-if="detailInfo.visible"
    v-model:visible="detailInfo.visible"
    :orderId="detailInfo.id"
    @returnBack="getList"
  />
  <PlanDetail
    v-if="planDetailInfo.visible"
    v-model:visible="planDetailInfo.visible"
    :tableRowId="planDetailInfo.id"
  ></PlanDetail>
  <excelOrPrint :excelPrint="excelPrint"></excelOrPrint>
  <page-dialog
    v-show="dialogInfo.visible"
    :title="dialogInfo.title"
    v-model:visible="dialogInfo.visible"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="asset-msg">
      <div class="asset-msg-label">
        <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
      </div>
      <el-radio-group v-model="dialogInfo.flag">
        <el-radio :label="true">当前页数据</el-radio>
        <el-radio :label="false">全部页数据</el-radio>
      </el-radio-group>
    </div>
  </page-dialog>
</template>
<script setup>
import {
  getInventorySurplusOrderDetailCustomizeListPage,
  getInventorySurplusOrderDetailCustomizeListAll,
  getInventorySurplusOrderDetailGroup,
  exportInventorySurplusOrderDetailList,
} from '@/api/asset.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { ElMessage } from 'element-plus'
import { selectByCodeAndDept } from '@/api/report.js'
import { doPrint } from '@/utils/exportUtil.js'
const OrderDetail = defineAsyncComponent(() => import('./detail'))
import PlanDetail from '../assetInventoryPlan/details'
import SetPreference from '@/components/SetPreference/defaultSetPreference'
const { proxy } = getCurrentInstance()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
})
const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: undefined, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
})
const filterInfo = ref({
  sortArr: [],
  query: {
    groupMap: {},
    groups: [],
    sortString: '',
    queryMap: {},
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      value: 'excel',
      type: 'slot',
      show: proxy.$permission('assetInventorySurplus:excel'),
    },
    {
      value: 'print',
      type: 'slot',
      show: proxy.$permission('assetInventorySurplus:printDetailList'),
    },
  ],
})
const clearType = ref(true)
const groupFlag = ref(false)
const slipSelectRequest = ref(true)
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  data: [],
  selections: [],
  fieldList: [],
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const planDetailInfo = ref({
  visible: false,
  id: '',
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})

function closeDetailList() {
  proxy.$store.dispatch('app/toggleOpenFilter')
  showDialog.value = false
  proxy.$emit('callback')
}
function updateGroupSelections(arr) {
  filterInfo.value.query.groups = arr
  groupSelectInfo.value.selections = arr
  if (!arr.length) {
    filterInfo.value.query.groups = []
    filterInfo.value.query.groupMap = {}
    groupSelectInfo.value.data = []
    groupFlag.value = false
  }
}
function groupSelect(arr) {
  if (arr.length) {
    //点击分组
    groupFlag.value = true
    filterInfo.value.query.groups = arr
    groupSelectInfo.value.selections = arr
    getCustomizeGroupsList()
  } else {
    ElMessage.warning({
      message: '请选择分组条件！',
      showClose: true,
      duration: 3000,
    })
  }
}
//导出excel
const excelPrint = ref({
  type: 'print', // 类型print/excel
  excel: {
    api: undefined, // 导出数据接口
    params: {}, // 导出参数
  },
  refresh: null,
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
//打印导出分页参数
function pageInfo(obj) {
  page.value = obj
}
//导出
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if ((dialogInfo.value.type = 'print')) {
    print()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
//导出excel
function exportExcelList() {
  exportInventorySurplusOrderDetailList({
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
  }).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function handelPrint() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
const popoverVisible = ref(false)
const templateArr = ref([])
async function print() {
  //打印
  selectByCodeAndDept({
    tempCode: 'assetInventorySurplusDetailList',
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        console.log(proxy.$refs.popoverShow)
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
              ...page.value,
              page: dialogInfo.value.flag,
            }),
          },
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      ...filterInfo.value.query,
    },
    callback: printCallback,
    data: {
      customParam: JSON.stringify({
        ...filterInfo.value.query,
        ...page.value,
        page: dialogInfo.value.flag,
      }),
    },
  })
  popoverVisible.value = false
}

function printCallback() {
  try {
    // 打印成功增加打印次数
    // updatePrintCount({
    //   orderNo: infoList.value.data.orderNo,
    //   orderId: props.orderId,
    //   tempCode: 'paymentDeatil',
    //   orderType: 0,
    // })
  } catch (error) {}
}
//导出excel
async function exportExcel() {
  dialogInfo.value.flag = true
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
}
async function getCustomizeGroupsList(len, param, expande) {
  //分组查询
  let params = {}
  if (len) {
    params = param
  } else {
    params = filterInfo.value.query
  }
  if (
    filterInfo.value.query.queryDtoList &&
    filterInfo.value.query.queryDtoList.length
  ) {
    params = proxy.$fn.deepClone(params)
    params.queryMap = {}
  }
  await getInventorySurplusOrderDetailGroup(params).then(async (res) => {
    if (res && res.success) {
      let data = res.data
      let newData = []
      if (len) {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ ...item, id: index + Math.random(), isColspan: true }],
          })
        })
        expande.children = newData
      } else {
        await data.forEach((item, index) => {
          newData.push({
            ...item,
            id: index + Math.random(),
            isColspan: true,
            children: [{ id: index + Math.random(), isColspan: true }],
          })
        })
        groupSelectInfo.value.data = newData
      }
    }
  })
}
function exChange(data, expandedRows) {
  //展开分组
  if (expandedRows) {
    let len = data.nextGroups.length
    if (len) {
      let params = {
        ...filterInfo.value.query,
        groups: data.nextGroups,
        groupMap: { ...data.query },
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getCustomizeGroupsList(len, params, data)
    } else {
      let params = {
        ...filterInfo.value.query,
        groups: [],
        groupMap: {},
        queryMap: { ...filterInfo.value.query.queryMap, ...data.query },
      }
      getInventorySurplusOrderDetailCustomizeListAll(params).then(
        async (res) => {
          if (res && res.success) {
            let resData = res.data
            await resData.forEach((item, index) => {
              item.id = index + Math.random()
              item.isColspan = false
            })
            data.children = resData
          }
        }
      )
    }
  } else {
    data.children = [{ id: Math.random(), isColspan: true }]
  }
}
function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  if (groupSelectInfo.value.selections.length > 0) {
    await getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    await getList()
  }
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  clearType.value = !clearType.value
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  if (groupSelectInfo.value.selections.length > 0) {
    getCustomizeGroupsList()
  } else {
    groupSelectInfo.value.data = []
    tableInfo.value.initCurpage = Math.random()
    tableInfo.value.refresh = Math.random()
  }
}
function showDetail(row) {
  detailInfo.value.id = row.orderId
  detailInfo.value.visible = true
}
function showPlanDetail(row) {
  planDetailInfo.value.id = row.planOrderId
  planDetailInfo.value.visible = true
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetManageAssetInventorySurplusDetailList-com.slip.spd.entity.vo.asset.AssetInventorySurplusOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = tableFieldInfo.fieldList
      groupSelectInfo.value.options = tableFieldInfo.groupOption
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = getInventorySurplusOrderDetailCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.toString()
    getList()
  }
}
function tableRowClassName(row) {
  if (row.row.nextGroups) {
    return 'bg-color-EBEEF5'
  } else {
    return ''
  }
}
function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (row.nextGroups) {
    if (columnIndex === 0) {
      return {
        rowspan: 1,
        colspan: tableInfo.value.fieldList.length,
      }
    }
  }
}

let obj = {
  orderNo: {
    label: '任务单号',
    value: 'orderNo',
    componentType: 'input',
    type: 'slot',
    show: false,
    hidden: true,
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()
</script>

<style scoped></style>
